<?php
class ControllerDeployConfirmDefault extends Controller {
    public function index() {
        $this->language->load('checkout/checkout');
        $this->load->model('tool/image');
        unset($this->session->data['app']);


        $total_price=0;
        $data = array();

        $this->load->model('catalog/product');


        $region='';
        //fixed build multi vpc and public-ip in same region
        $region_arr = array();
		
		
        foreach ($this->cart->getProducts() as $product) {
            $passoword=$this->backend->createRandomStr();
            foreach ($product['option'] as $option) {
                //get region
                if($option['option_description_label']=='region'&&$region!=$option['option_value']&&!isset($region_arr[$option['option_value']])){
                  //fixed build multi vpc and public-ip in same region
                    $region_arr[$option['option_value']] = $option['option_value'];
                   //end 
                    $region=$option['option_value'];
                    $salt=substr(md5(uniqid(rand(), true)), 0, 9);
                    $vpcname = "vpc_".$salt;
                    $eipname = "eip_".$salt;
                    $subnetname = "subnet_".$salt;

                    $this->session->data['app']['eip_deploy'][]= array(
                        'url'=>'public_ip',
                        'cmd'=>'post',
                        'params'=>array(
                            'username'=>$this->customer->getEmail(),
                            'name'=>$eipname,
                            'bandwidth'=>1,
                            'region'=>$region,
                        )
                    );

                    $this->session->data['app']['vpc_deploy'][]= array(
                        'url'=>'vpc',
                        'cmd'=>'post',
                        'params'=>array(
                            'username'=>$this->customer->getEmail(),
                            'name'=>$vpcname,
                            'public_ip_name'=>$eipname,
                            'region'=>$region,
                            "vxnet"=>array(
                                array(
                                    "vxnet_name"=>$subnetname,
                                    "vxnet_network"=>"192.168.1.0/24"
                                )
                            )
                        )
                    );


                }



                if ($option['type'] != 'file') {
                    $value = $option['option_value'];
                } else {
                    $filename = $this->encryption->decrypt($option['option_value']);

                    $value = utf8_substr($filename, 0, utf8_strrpos($filename, '.'));
                }

                $option_data[] = array(
                    'name'  => $option['name'],
                    'value' =>$value
                );
            }





            foreach($option_data as $result){
                $app_deploy_option[$result['name']]= $result['value'];

            }

            $deploy_config=$this->model_catalog_product->getProductDeploy($product['product_id']);

            $salt=substr(md5(uniqid(rand(), true)), 0, 9);

            $model_array=explode('_',$product['model']);
            $app_name=$model_array['1'];
            if(strlen($app_name)<3){
                $app_name=$app_name."_server";
            }

            if($app_deploy_option['host_type']){
                $instance_type=$app_deploy_option['host_type'];
            }else{
                $instance_type='c1m1';
            }
            if($app_deploy_option['os_type']){
                $os_type=$app_deploy_option['os_type'];
            }else {
                $os_type = 'ubuntu-12.04';
            }


            $parameter_array['instance_type']=$instance_type;
            $parameter_array['os_type']=$os_type;


            if($deploy_config['db_mysql']){
                $parameter_array['db_mysql']=array(
                    "mysql_db_name" =>$deploy_config['mysql_db_name'],
                    "mysql_db_user" =>$deploy_config['mysql_db_user'],
                    "mysql_db_password" =>$deploy_config['mysql_db_password'],
                    "mysql_root_password" =>$deploy_config['mysql_root_password'],
                );
            }
            if($deploy_config['windows_server_ad']){
                $parameter_array['windows_server_ad']=array(
                    "windows_domain_name" =>$deploy_config['windows_domain_name'],
                    "windows_netbios_name" =>$deploy_config['windows_netbios_name'],
                    "windows_safe_admin_password" =>$passoword
                );
            }



            if($deploy_config['web_control_status']){
                $parameter_array['access_app_control']['web_control']=array(
                    "is_allowed"  => true,
                    "port_mapping"  => (int)$deploy_config['web_control_value']
                );
            }
            if($deploy_config['https_control_status']){
                $parameter_array['access_app_control']['https_control']=array(
                    "is_allowed"  => true,
                    "port_mapping"  => (int)$deploy_config['https_control_value']
                );
            }
            if($deploy_config['ssh_control_status']){
                $parameter_array['access_app_control']['ssh_control']=array(
                    "is_allowed"  => true,
                    "port_mapping"  => (int)$deploy_config['ssh_control_value']
                );
            }
            if($deploy_config['mstsc_control_status']){
                $parameter_array['access_app_control']['mstsc_control']=array(
                    "is_allowed"  => true,
                    "port_mapping"  => (int)$deploy_config['mstsc_control_value']
                );
            }
            if($deploy_config['webmail_control_status']){
                $parameter_array['access_app_control']['webmail_control']=array(
                    "is_allowed"  => true,
                    "port_mapping"  => (int)$deploy_config['webmail_control_value']
                );
            }
            if($deploy_config['web_redirect_control_status']){
                $parameter_array['access_app_control']['web_redirect_control']=array(
                    "is_allowed"  => true,
                    "port_mapping"  => (int)$deploy_config['web_redirect_control_value']
                );
            }
            if($deploy_config['web_work_control_status']){
                $parameter_array['access_app_control']['web_work_control']=array(
                    "is_allowed"  => true,
                    "port_mapping"  => (int)$deploy_config['web_work_control_value']
                );
            }
            if($deploy_config['pop3_control_status']){
                $parameter_array['access_app_control']['pop3_control']=array(
                    "is_allowed"  => true,
                    "port_mapping"  => (int)$deploy_config['pop3_control_value']
                );
            }
            if($deploy_config['smtp_control_status']){
                $parameter_array['access_app_control']['smtp_control']=array(
                    "is_allowed"  => true,
                    "port_mapping"  => (int)$deploy_config['smtp_control_value']
                );
            }
            if($deploy_config['imap_control_status']){
                $parameter_array['access_app_control']['imap_control']=array(
                    "is_allowed"  => true,
                    "port_mapping"  => (int)$deploy_config['imap_control_value']
                );
            }
            if($deploy_config['server_control_status']){
                $parameter_array['access_app_control']['server_control']=array(
                    "is_allowed"  => true,
                    "port_mapping"  => (int)$deploy_config['server_control_value']
                );
            }
            if($deploy_config['file_server_control_status']){
                $parameter_array['access_app_control']['file_server_control']=array(
                    "is_allowed"  => true,
                    "port_mapping"  => (int)$deploy_config['file_server_control_value']
                );
            }
            if($deploy_config['upgradesvr_control_status']){
                $parameter_array['access_app_control']['upgradesvr_control']=array(
                    "is_allowed"  => true,
                    "port_mapping"  => (int)$deploy_config['upgradesvr_control_value']
                );
            }
            if($deploy_config['SessionServer_control_status']){
                $parameter_array['access_app_control']['SessionServer_control']=array(
                    "is_allowed"  => true,
                    "port_mapping"  => (int)$deploy_config['SessionServer_control_value']
                );
            }
            if($deploy_config['infoServer_control_status']){
                $parameter_array['access_app_control']['infoServer_control']=array(
                    "is_allowed"  => true,
                    "port_mapping"  => (int)$deploy_config['infoServer_control_value']
                );
            }
            if($deploy_config['offmsgsvr_control_status']){
                $parameter_array['access_app_control']['offmsgsvr_control']=array(
                    "is_allowed"  => true,
                    "port_mapping"  => (int)$deploy_config['offmsgsvr_control_value']
                );
            }




            $this->session->data['app']['deploy_config'][$product['product_id']]=array(
                'url'=>"app_api",
                'cmd'=>"post",
                'params'=>array(
                    'username'   =>$this->customer->getEmail(),
                    'app_type'   =>$product['model'].$this->cart->getAppVersion($product['product_id']),
                    'name'   =>$app_name."_".$salt,
                    'region'   =>$region,
                    'network'   =>array(
                        "network_type" => "vpc",
                        "vpc_mode"       => array(
                            "vpc_name"           =>$vpcname,
                            "vxnet_name"        =>$subnetname,
                        )
                    ),
                    "administrator"  =>array(
                        "admin_mode" =>"password",
                        "password" =>$passoword,
                    ),
                    "parameter"     =>$parameter_array
                )
            );

            $this->session->data['app']['appconfig'][$product['product_id']]=array(
                'appname'   =>$product['model']."_". $this->customer->getId()."_".$salt,
                'vpc'   =>$vpcname,
                'subnet'   =>$subnetname,
            );



        }

        $this->load->model('checkout/order');

        $this->data['column_name'] = $this->language->get('column_name');
        $this->data['column_model'] = $this->language->get('column_model');
        $this->data['column_quantity'] = $this->language->get('column_quantity');
        $this->data['column_price'] = $this->language->get('column_price');
        $this->data['column_total'] = $this->language->get('column_total');

        $this->data['text_recurring_item'] = $this->language->get('text_recurring_item');
        $this->data['text_payment_profile'] = $this->language->get('text_payment_profile');

        $this->data['payment'] = $this->getChild('payment/cod');
        $this->data['products'] = array();

        foreach ($this->cart->getProducts() as $product) {
            $option_data = array();

            if ($product['image']) {
            	$image = $this->model_tool_image->resize($product['image'], $this->config->get('config_image_cart_width'), $this->config->get('config_image_cart_height'));
            } else {
            	$image = '';
            }



            foreach ($product['option'] as $option) {
                if ($option['type'] != 'file') {
                    $value = $option['option_value'];
                } else {
                    $filename = $this->encryption->decrypt($option['option_value']);

                    $value = utf8_substr($filename, 0, utf8_strrpos($filename, '.'));
                }

                $option_data[] = array(
                    'name'  => $option['name'],
                    'value' => $value
                );
            }


            $profile_description = '';

            if ($product['recurring']) {
                $frequencies = array(
                    'day' => $this->language->get('text_day'),
                    'week' => $this->language->get('text_week'),
                    'semi_month' => $this->language->get('text_semi_month'),
                    'month' => $this->language->get('text_month'),
                    'year' => $this->language->get('text_year'),
                );

                if ($product['recurring_trial']) {
                    $recurring_price = $this->currency->format($this->tax->calculate($product['recurring_trial_price'] * $product['quantity'], $product['tax_class_id'], $this->config->get('config_tax')));
                    $profile_description = sprintf($this->language->get('text_trial_description'), $recurring_price, $product['recurring_trial_cycle'], $frequencies[$product['recurring_trial_frequency']], $product['recurring_trial_duration']) . ' ';
                }

                $recurring_price = $this->currency->format($this->tax->calculate($product['recurring_price'] * $product['quantity'], $product['tax_class_id'], $this->config->get('config_tax')));

                if ($product['recurring_duration']) {
                    $profile_description .= sprintf($this->language->get('text_payment_description'), $recurring_price, $product['recurring_cycle'], $frequencies[$product['recurring_frequency']], $product['recurring_duration']);
                } else {
                    $profile_description .= sprintf($this->language->get('text_payment_until_canceled_description'), $recurring_price, $product['recurring_cycle'], $frequencies[$product['recurring_frequency']], $product['recurring_duration']);
                }
            }
            //get instance price
            $paramter=(array)$this->session->data['app']['deploy_config'][$product['product_id']]['params']['parameter'];
            $host_type=$paramter['instance_type'];
            $os_type=$paramter['os_type'];
            $region=$this->session->data['app']['deploy_config'][$product['product_id']]['params'][
            'region'];

            $host_data=array(
                'cloud_type' => 'qingyun',
                'region' => $region,
                'host_type' => $host_type,
                'os_type' => $os_type,
            );

            $host_price=$this->price->getPrice($host_data);


            $total_price=$total_price+$host_price;

            $this->data['products'][] = array(
                'key'                 => $product['key'],
                'product_id'          => $product['product_id'],
                'name'                => $product['name'],
                'app_name'                => $this->session->data['app']['deploy_config'][$product['product_id']]['params']['name'],
                'instance_type'                => $this->session->data['app']['deploy_config'][$product['product_id']]['params']['parameter']['instance_type'],
                'model'               => $product['model'],
                'image'               => $image,
                'option'              => $option_data,
                'quantity'            => $product['quantity'],
                'subtract'            => $product['subtract'],
                'hour_price'               => $this->currency->format($this->tax->calculate($host_price, $product['tax_class_id'], $this->config->get('config_tax'))),
                'month_price'               => $this->currency->format($this->tax->calculate($host_price*720, $this->config->get('config_tax_id'), $this->config->get('config_tax')),2),
                'href'                => $this->url->link('product/product', 'product_id=' . $product['product_id']),
                'recurring'           => $product['recurring'],
                'profile_name'        => $product['profile_name'],
                'profile_description' => $profile_description,
            );



            $data['product_deploy'][]=array(
                'order_product_id'          => $product['product_id'],
                'app_name'                => $this->session->data['app']['deploy_config'][$product['product_id']]['params']['name'],
                'vpc_name'                => $this->session->data['app']['deploy_config'][$product['product_id']]['params']['network']['vpc_mode']['vpc_name'],
                'subnet_name'                => $this->session->data['app']['deploy_config'][$product['product_id']]['params']['network']['vpc_mode']['vxnet_name'],
                'instance_type'                => $this->session->data['app']['deploy_config'][$product['product_id']]['params']['parameter']['instance_type'],
                'super_password'                => $passoword,
                'price'                =>$host_price
            );

        }



        $data['invoice_prefix'] = $this->config->get('config_invoice_prefix');
        $data['store_id'] = $this->config->get('config_store_id');
        $data['store_name'] = $this->config->get('config_name');

        if ($data['store_id']) {
            $data['store_url'] = $this->config->get('config_url');
        } else {
            $data['store_url'] = HTTP_SERVER;
        }

        if ($this->customer->isLogged()) {
            $data['customer_id'] = $this->customer->getId();
            $data['customer_group_id'] = $this->customer->getCustomerGroupId();
            $data['firstname'] = $this->customer->getFirstName();
            $data['lastname'] = $this->customer->getLastName();
            $data['email'] = $this->customer->getEmail();
            $data['telephone'] = $this->customer->getTelephone();
            $data['fax'] = $this->customer->getFax();

            $this->load->model('account/address');

        } elseif (isset($this->session->data['guest'])) {
            $data['customer_id'] = 0;
            $data['customer_group_id'] = $this->session->data['guest']['customer_group_id'];
            $data['firstname'] = $this->session->data['guest']['firstname'];
            $data['lastname'] = $this->session->data['guest']['lastname'];
            $data['email'] = $this->session->data['guest']['email'];
            $data['telephone'] = $this->session->data['guest']['telephone'];
            $data['fax'] = $this->session->data['guest']['fax'];

        }

        $data['payment_firstname'] = "";
        $data['payment_lastname'] = "";
        $data['payment_company'] = "";
        $data['payment_company_id'] = "";
        $data['payment_tax_id'] = "";
        $data['payment_address_1'] = "";
        $data['payment_address_2'] = "";
        $data['payment_city'] = "";
        $data['payment_postcode'] = "";
        $data['payment_zone'] = "";
        $data['payment_zone_id'] = "";
        $data['payment_country'] = "";
        $data['payment_country_id'] = "";
        $data['payment_address_format'] = "";

        $data['payment_method'] = '';

        $data['payment_code'] = '';


        $data['shipping_firstname'] = '';
        $data['shipping_lastname'] = '';
        $data['shipping_company'] = '';
        $data['shipping_address_1'] = '';
        $data['shipping_address_2'] = '';
        $data['shipping_city'] = '';
        $data['shipping_postcode'] = '';
        $data['shipping_zone'] = '';
        $data['shipping_zone_id'] = '';
        $data['shipping_country'] = '';
        $data['shipping_country_id'] = '';
        $data['shipping_address_format'] = '';
        $data['shipping_method'] = '';
        $data['shipping_code'] = '';





        $product_data = array();

        foreach ($this->cart->getProducts() as $product) {
            $option_data = array();

            if ($product['image']) {
            	$image = $this->model_tool_image->resize($product['image'], $this->config->get('config_image_cart_width'), $this->config->get('config_image_cart_height'));
            } else {
            	$image = '';
            }


            //get instance price


            $paramter=(array)$this->session->data['app']['deploy_config'][$product['product_id']]['params']['parameter'];
            $host_type=$paramter['instance_type'];
            $os_type=$paramter['os_type'];
            $region=$this->session->data['app']['deploy_config'][$product['product_id']]['params'][
            'region'];

            $host_data=array(
                'cloud_type' => 'qingyun',
                'region' => $region,
                'host_type' => $host_type,
                'os_type' => $os_type,
            );

            $host_price=$this->price->getPrice($host_data);




            foreach ($product['option'] as $option) {
                if ($option['type'] != 'file') {
                    $value = $option['option_value'];
                } else {
                    $value = $this->encryption->decrypt($option['option_value']);
                }

                $option_data[] = array(
                    'product_option_id'       => $option['product_option_id'],
                    'product_option_value_id' => $option['product_option_value_id'],
                    'option_id'               => $option['option_id'],
                    'option_value_id'         => $option['option_value_id'],
                    'name'                    => $option['name'],
                    'value'                   => $value,
                    'type'                    => $option['type']
                );
            }

            $product_data[] = array(
                'product_id' => $product['product_id'],
                'name'       => $product['name'],
                'model'      => $product['model'],
                'option'     => $option_data,
            	'image'      => $image,
                'download'   => $product['download'],
                'quantity'   => $product['quantity'],
                'subtract'   => $product['subtract'],
                'price'      => $host_price,
                'total'      => $product['total'],
                'tax'        => $this->tax->getTax($product['price'], $product['tax_class_id']),
                'reward'     => $product['reward']
            );
        }

        // Gift Voucher
        $voucher_data = array();

        if (!empty($this->session->data['vouchers'])) {
            foreach ($this->session->data['vouchers'] as $voucher) {
                $voucher_data[] = array(
                    'description'      => $voucher['description'],
                    'code'             => substr(md5(mt_rand()), 0, 10),
                    'to_name'          => $voucher['to_name'],
                    'to_email'         => $voucher['to_email'],
                    'from_name'        => $voucher['from_name'],
                    'from_email'       => $voucher['from_email'],
                    'voucher_theme_id' => $voucher['voucher_theme_id'],
                    'message'          => $voucher['message'],
                    'amount'           => $voucher['amount']
                );
            }
        }

        $data['products'] = $product_data;
        $data['vouchers'] = $voucher_data;
        $data['totals'] = "";
        $data['comment'] = "";
        if (isset($this->request->cookie['tracking'])) {
            $this->load->model('affiliate/affiliate');

            $affiliate_info = $this->model_affiliate_affiliate->getAffiliateByCode($this->request->cookie['tracking']);
            $subtotal = $this->cart->getSubTotal();

            if ($affiliate_info) {
                $data['affiliate_id'] = $affiliate_info['affiliate_id'];
                $data['commission'] = ($subtotal / 100) * $affiliate_info['commission'];
            } else {
                $data['affiliate_id'] = 0;
                $data['commission'] = 0;
            }
        } else {
            $data['affiliate_id'] = 0;
            $data['commission'] = 0;
        }

        $data['language_id'] = $this->config->get('config_language_id');
        $data['currency_id'] = $this->currency->getId();
        $data['currency_code'] = $this->currency->getCode();
        $data['currency_value'] = $this->currency->getValue($this->currency->getCode());
        $data['ip'] = $this->request->server['REMOTE_ADDR'];

        if (!empty($this->request->server['HTTP_X_FORWARDED_FOR'])) {
            $data['forwarded_ip'] = $this->request->server['HTTP_X_FORWARDED_FOR'];
        } elseif(!empty($this->request->server['HTTP_CLIENT_IP'])) {
            $data['forwarded_ip'] = $this->request->server['HTTP_CLIENT_IP'];
        } else {
            $data['forwarded_ip'] = '';
        }

        if (isset($this->request->server['HTTP_USER_AGENT'])) {
            $data['user_agent'] = $this->request->server['HTTP_USER_AGENT'];
        } else {
            $data['user_agent'] = '';
        }

        if (isset($this->request->server['HTTP_ACCEPT_LANGUAGE'])) {
            $data['accept_language'] = $this->request->server['HTTP_ACCEPT_LANGUAGE'];
        } else {
            $data['accept_language'] = '';
        }



        //eip&vpc set
        if(isset($this->session->data['app']['eip_deploy'])){
            foreach($this->session->data['app']['eip_deploy'] as $eip){
                //get eip price
                //get eip price
                $eip_data=array(
                    'cloud_type' => 'qingyun',
                    'region' => $eip['params']['region'],
                    'bandwidth' => $eip['params']['bandwidth'],
                );

                $eip_price=$this->price->getPrice($eip_data);
                $total_price=$total_price+$eip_price;
                $this->data['eips'][]=array(
                    'eip_image'                => $this->model_tool_image->resize('data/eip_icon.jpg', $this->config->get('config_image_cart_width'), $this->config->get('config_image_cart_height')),
                    'eip_name'                => $eip['params']['name'],
                    'bandwidth'                =>$eip['params']['bandwidth'],
                    'hour_price'               => $this->currency->format($this->tax->calculate($eip_price, 0, $this->config->get('config_tax'))),
                    'month_price'               =>  $this->currency->format($this->tax->calculate($eip_price*720, $this->config->get('config_tax_id'), $this->config->get('config_tax'))),2);

                $data['eips_info'][]=array(
                    'eip_name'                => $eip['params']['name'],
                    'bandwidth'                =>$eip['params']['bandwidth'],
                    'price'               => $eip_price
                );

            }
        }
        if(isset($this->session->data['app']['vpc_deploy'])){
            foreach($this->session->data['app']['vpc_deploy'] as $vpc){
                //get vpc _price
                $vpc_data=array(
                    'cloud_type' => 'qingyun',
                    'region' => $vpc['params']['region'],
                    'vpc_type' => 'small',
                );
                $vpc_price=$this->price->getPrice($vpc_data);
                $total_price=$total_price+$vpc_price;
                $this->data['vpc_price'][]=array(
                    'vpc_image'                => $this->model_tool_image->resize('data/vpc_icon.jpg', $this->config->get('config_image_cart_width'), $this->config->get('config_image_cart_height')),
                    'vpc_name'                => $vpc['params']['name'],
                    'vpc_type'                => 'Small',
                    'hour_price'               => $this->currency->format($this->tax->calculate($vpc_price, 0, $this->config->get('config_tax'))),
                    'month_price'               =>  $this->currency->format($this->tax->calculate($vpc_price*720, $this->config->get('config_tax_id'), $this->config->get('config_tax')),2)
                );
                $data['vpc_price_info'][]=array(
                    'vpc_name'                => $vpc['params']['name'],
                    'vpc_type'                =>'标准',
                    'price'               => $vpc_price
                );
            }
        }


        $data['total'] = $total_price;

        $this->data['month_total'] =$this->currency->format($this->tax->calculate($total_price*720, $this->config->get('config_tax_id'), $this->config->get('config_tax')),2);
        $this->data['hour_total'] = $this->currency->format($this->tax->calculate($total_price, 0 , $this->config->get('config_tax')));

        $this->session->data['order_id'] = $this->model_checkout_order->addOrder($data);



        if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/deploy/deploy_confirm.tpl')) {
            $this->template = $this->config->get('config_template') . '/template/deploy/deploy_confirm.tpl';
        } else {
            $this->template = 'default/template/deploy/deploy_confirm.tpl';
        }

        $this->response->setOutput($this->render());
    }

}
?>
